/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/binary-tree-postorder-traversal
   @Language: C++
   @Datetime: 19-07-09 17:21
   */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

// Method 1, recursion
class Solution {
	void postorder(TreeNode *root, vector<int> &v){
		if(root->left) postorder(root->left,v);
		if(root->right) postorder(root->right,v);
		v.push_back(root->val);
	}
public:
	vector<int> postorderTraversal(TreeNode* root) {
		vector<int> v;
		if(root==NULL) return v;
		postorder(root,v);
		return v;
	}
};

// Method 2, loop
class Solution {
public:
	vector<int> postorderTraversal(TreeNode* root) {
		vector<int> v;
		if(root==NULL) return v;
		stack<TreeNode*> s;
		for(s.push(root); s.size();){
			root=s.top();
			s.pop();
			if(root->left) s.push(root->left);
			if(root->right) s.push(root->right);
			v.push_back(root->val);
		}
		reverse(v.begin(),v.end());
		return v;
	}
};
